package handler

import (
	"2302a/testyuekao/api/request"
	"2302a/testyuekao/api/resp"
	"2302a/testyuekao/internal/dao"
	"2302a/testyuekao/internal/model"
	"github.com/gin-gonic/gin"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrderReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.UType != 1 {
		resp.Error(c, 100002, "该权限不足", nil)
		return
	}
	var house model.Houses
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		resp.Error(c, 100003, "房源信息不存在", nil)
		return
	}
	order := model.Orders{
		UserId:     userId,
		HouseId:    req.HouseId,
		Price:      house.Price,
		VoucherUrl: house.FileUrl,
	}
	dao.Create(&order)
	resp.Success(c, "创建购房成功", true)

}

func VoucherOrder(c *gin.Context) {
	var req request.VoucherOrderReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var order model.Orders
	dao.GetOneById(req.Id, &order)
	if order.Id == 0 {
		resp.Error(c, 100003, "订单信息不存在", nil)
		return
	}
	dao.Update(&model.Orders{Id: req.Id, VoucherUrl: req.VoucherUrl, Status: 2})
	resp.Success(c, "首付款凭证接成功", true)
}

func AdminViewOrder(c *gin.Context) {
	var req request.AdminViewOrderReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.UType != 3 {
		resp.Error(c, 100002, "用户该权限不足", nil)
		return
	}
	var order model.Orders
	dao.GetOneById(req.Id, &order)
	if order.Id == 0 {
		resp.Error(c, 100003, "订单信息不存在", nil)
		return
	}
	resp.Success(c, "管理员查看订单成功", order)
}

func AdminUpdateStatusOrder(c *gin.Context) {
	var req request.AdminUpdateStatusOrderReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.UType != 3 {
		resp.Error(c, 100002, "用户该权限不足", nil)
		return
	}
	var order model.Orders
	dao.GetOneById(req.Id, &order)
	if order.Id == 0 {
		resp.Error(c, 100003, "订单信息不存在", nil)
		return
	}
	dao.Update(&model.Orders{Id: req.Id, Status: req.Status})
	resp.Success(c, "管理员修改状态成功", true)
}
